<template>
  <div :class="{ hideUpload: limit == uploadFileList.length }">
    <el-upload
      ref="upload"
      v-loading="uploading"
      action=""
      list-type="picture-card"
      accept="image/*"
      :limit="limit"
      :file-list="uploadFileList"
      :disabled="disable"
      :http-request="params => handleFile(params)"
      :on-remove="handleRemove"
    >
      <!-- :on-preview="handlePictureCardPreview" -->
      <i slot="default" class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    urlList: {
      type: Array,
      default: () => ([])
    },
    disabled: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: null
    },
  },
  data () {
    return {
      uploadFileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      disable: false,
      uploading: false,
    };
  },
  watch: {
    urlList (val) {
      this.uploadFileList = val || []
    },
    disabled (val) {
      this.disable = val
    },
  },
  mounted () {
    this.uploadFileList = this.urlList || []
    this.disable = this.disabled
  },
  methods: {
    handleRemove (file) {
      var index = this.uploadFileList.findIndex(a => a.name === file.name)
      if (index !== -1) {
        this.uploadFileList.splice(index, 1);
        this.getFile()
      }
    },
    // 上传文件
    handleFile (files) {
      this.uploading = true
      let { file } = files
      this.getBase64(file).then(res => {
        if (res) {
          let name = res.substring(0, 9)
          this.uploadFileList.push({ url: res, name })
          this.getFile()
          this.uploading = false
        }
      })
    },
    getFile() {
      this.$emit('getFile', this.uploadFileList)
    },
    clearFile() {
      this.$refs.upload && this.$refs.upload.clearFiles()
    },
    // 转base64
    getBase64(data) {
      return new Promise((resolve, reject) => {
        const blob = new Blob([data], { type: "image/jpg" }); // 类型一定要写！！！
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.hideUpload {
  ::v-deep .el-upload{
    display: none;
  }
}
::v-deep .el-upload--picture-card {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  line-height: 146px;
  vertical-align: top;
}
</style>
